﻿using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using FutureApp.MultiTenancy;
using FutureApp.Users;
using Microsoft.AspNet.Identity;

namespace FutureApp
{
    /// <summary>
    /// Derive your application services from this class.
    /// </summary>
    public abstract class FutureAppAppServiceBase : ApplicationService
    {
        /// <summary>
        /// 租户管理器
        /// </summary>
        public TenantManager TenantManager { get; set; }

        /// <summary>
        /// 用户管理器
        /// </summary>
        public UserManager UserManager { get; set; }

        /// <constructor/>
        protected FutureAppAppServiceBase()
        {
            this.LocalizationSourceName = FutureAppConsts.LocalizationSourceName;
        }

        /// <summary>
        /// 异步获取当前用户
        /// </summary>
        protected virtual Task<User> GetCurrentUserAsync()
        {
            var user = this.UserManager.FindByIdAsync(this.AbpSession.GetUserId());
            if (user == null) throw new ApplicationException("There is no current user!");
            return user;
        }

        /// <summary>
        /// 异步获取当前租户
        /// </summary>
        protected virtual Task<Tenant> GetCurrentTenantAsync()
        {
            return this.TenantManager.GetByIdAsync(this.AbpSession.GetTenantId());
        }

        /// <summary>
        /// 检查返回结果中的错误
        /// </summary>
        protected virtual void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(this.LocalizationManager);
        }
    }
}